<?php

OaTranslates::import('role');

class OaRoles extends \Formax\Model
{

    const SALES_DIRECTOR = 3;
    const SALES_MANANGER = 4;
    const SALES_STAFF = 5;

    /**
     *
     * @var integer
     */
    public $dept_id = 0;

    /**
     *
     * @var integer
     */
    public $role_id;

    /**
     *
     * @var integer
     */
    public $protected = 0;

    /**
     *
     * @var string
     */
    public $description = '';

    /**
     *
     * @var integer
     */
    public $sort_order = 99;

    // 删除操作
    public function delete()
    {
        if ($this->protected) return false;

        // 删除用户角色
        OaUserRoles::find('role_id=' . $this->role_id)->delete();

        // 删除访问列表
        OaAccessList::find('role_id=' . $this->role_id)->delete();

        // 删除对应翻译
        OaTranslates::find("keyword='role' and foreign_id={$this->role_id}")->delete();

        return parent::delete();
    }

    // 获取所有的角色
    public static function getAll()
    {
        static $cached = null;

        if ($cached === null) {
            $rows = self::find(array('order' => 'sort_order desc'))->toArray();

            $cached = array();
            foreach ($rows as $row) {
                $row['department'] = OaDepartments::getOne($row['dept_id']);
                $cached[$row['role_id']] = $row;
            }
        }

        return $cached;
    }

    // 获取角色信息
    public static function getOne($user_id)
    {
        return array_get(self::getAll(), $user_id);
    }

}
